package top.lcm889.juc.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author Coder-lcm
 * @date 2021/6/4
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        int shareResourceCount = 3;
        int totalRequestCount = 18;
        // 信号量，即共享资源的数量
        Semaphore semaphore = new Semaphore(shareResourceCount);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < totalRequestCount; i++) {
            executorService.execute(() -> {
                try {
                    // 申请资源
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + " 申请到资源, 剩余可用资源数：" + semaphore.availablePermits());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    // 释放资源
                    semaphore.release();
                }
            });
        }
        executorService.shutdown();
    }
}
